package com.github.uiautomator

import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.GestureDescription
import android.accessibilityservice.GestureDescription.StrokeDescription
import android.content.Intent
import android.graphics.Path
import android.graphics.Rect
import android.os.PowerManager
import android.os.PowerManager.WakeLock
import android.util.Log
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityNodeInfo
import java.io.File
import java.io.FileOutputStream


class AutoTaskService : AccessibilityService() {
    // 打印布局树的递归方法
    private fun printLayoutInfo(node: AccessibilityNodeInfo?, depth: Int) {
        if (node == null) return

        // 打印当前节点的信息
        val log = StringBuilder()
        for (i in 0 until depth) log.append("--")
        log.append("Class: ").append(node.className)
        log.append(", Text: ").append(node.text)
        log.append(", Content Description: ").append(node.contentDescription)
        log.append(", Clickable: ").append(node.isClickable)
        log.append(", Focusable: ").append(node.isFocusable)
        Log.e("LayoutInfo", log.toString())

        // 遍历子节点
        for (i in 0 until node.childCount) {
            printLayoutInfo(node.getChild(i), depth + 1)
        }
    }

    override fun onCreate() {
        super.onCreate()
        Log.i(TAG, "onCreate")
        accessibilityService = this
    }

    override fun onAccessibilityEvent(event: AccessibilityEvent) {
//                    // 当窗口状态改变时，尝试获取布局信息
        accessibilityService = this

        when (event.eventType) {
            AccessibilityEvent.TYPE_VIEW_CLICKED -> handleViewClicked(event)
            AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED -> handleWindowStateChanged(event)
            AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED -> handleTextChanged(event)
            AccessibilityEvent.TYPE_VIEW_SCROLLED -> handleViewScrolled(event)
            AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED -> handleNotification(event)
//            else -> Log.d("AccessibilityLog", "未处理的事件类型: ${event.eventType}")
        }

//        Log.i(TAG, "onAccessibilityEvent->" + event.getClassName());
        val rootNode = rootInActiveWindow
        if (rootNode != null && isLog) {
//            printLayoutInfo(rootNode, 0);
//            AccessibilityHelper.printRootNodeInfo(rootNode);
        }

        //        int eventType = event.getEventType();
//        switch (eventType) {
//            case AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED:
//                handleNotification(event);
//                break;
//            case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
//            case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED:
//                Log.i(TAG, "getClassName->" + event.getClassName());
//                if (event.getClassName() != null) {
//                    String className = event.getClassName().toString();
//                    if (className.contains("com.tencent.mm.ui.LauncherUI")) {
//                        getPacket(getRootInActiveWindow());
//                    } else if (className.contains("com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyNotHookReceiveUI")) {
//                        openPacket();
//                    } else if (className.contains("com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyDetailUI")) {
//                        close();
//                    } else {
//                        //getPacket(getRootInActiveWindow());
//                    }
//                }
//                break;
//        }
    }

    //    /**
    //     * 处理通知栏信息 * * 如果是微信红包的提示信息,则模拟点击 * * @param event
    //     */
    //    private void handleNotification(AccessibilityEvent event) {
    //        List<CharSequence> texts = event.getText();
    //        if (!texts.isEmpty()) {
    //            for (CharSequence text : texts) {
    //                String content = text.toString(); //如果微信红包的提示信息,则模拟点击进入相应的聊天窗口
    //                if (content.contains("[微信红包]")) {
    //                    if (event.getParcelableData() != null && event.getParcelableData() instanceof Notification) {
    //                        Notification notification = (Notification) event.getParcelableData();
    //                        PendingIntent pendingIntent = notification.contentIntent;
    //                        try {
    //                            pendingIntent.send();
    //                        } catch (PendingIntent.CanceledException e) {
    //                            e.printStackTrace();
    //                        }
    //                    }
    //                }
    //            }
    //        }
    //    }
    //
    //    /**
    //     * 关闭红包详情界面,实现自动返回聊天窗口
    //     */
    //    private void close() {
    //        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
    //        if (nodeInfo != null) { //为了演示,直接查看了关闭按钮的id
    //            List<AccessibilityNodeInfo> infos = nodeInfo.findAccessibilityNodeInfosByText("返回");
    //            nodeInfo.recycle();
    //            for (AccessibilityNodeInfo item : infos) {
    //                item.performAction(AccessibilityNodeInfo.ACTION_CLICK);
    //            }
    //            result = null;
    //            //performGlobalAction(GLOBAL_ACTION_HOME);
    //        }
    //    }
    //
    //    /**
    //     * 模拟点击,拆开红包
    //     */
    //    private void openPacket() {
    //        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
    //        if (nodeInfo != null) {
    //            //为了演示,直接查看了红包控件的id
    //            List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByText("开");
    //            for (AccessibilityNodeInfo item : list) {
    //                item.performAction(AccessibilityNodeInfo.ACTION_CLICK);
    //            }
    //        }
    //        nodeInfo.recycle();
    //    }
    //
    //    private AccessibilityNodeInfo result;
    //
    //    /**
    //     * 模拟点击,打开抢红包界面
    //     */
    //    private void getPacket(AccessibilityNodeInfo rootNode) {
    //        findRedBagNodes(rootNode);
    //        if (result != null) {
    //            Rect rect = new Rect();
    //            result.getBoundsInScreen(rect);
    //            int x = ((rect.left + rect.right) / 2);
    //            int y = ((rect.top + rect.bottom) / 2);
    //            click((float) x, (float) y);
    //        }
    //    }
    override fun onInterrupt() {
    }

    private fun handleViewClicked(event: AccessibilityEvent) {
        val node = event.source ?: return
        val rect = Rect()
        node.getBoundsInScreen(rect)
        val clickedText = node.text ?: "未知按钮"
        val log =
            "点击事件 - 文本: $clickedText, 坐标: (${rect.left}, ${rect.top}) 到 (${rect.right}, ${rect.bottom})\n"
        writeLog(log)
    }

    private fun handleWindowStateChanged(event: AccessibilityEvent) {
        val packageName = event.packageName ?: "未知应用"
        val className = event.className ?: "未知界面"
        val log = "界面跳转 - 应用: $packageName, 界面: $className\n"
        writeLog(log)
    }

    private fun handleTextChanged(event: AccessibilityEvent) {
        val textBefore = event.beforeText ?: ""
        val textAfter = event.text?.joinToString("") ?: ""
        val log = "文字输入 - 原内容: $textBefore, 当前内容: $textAfter\n"
        writeLog(log)
    }

    private fun handleViewScrolled(event: AccessibilityEvent) {
        val scrollX = event.scrollX
        val scrollY = event.scrollY
        val maxScrollX = event.maxScrollX
        val maxScrollY = event.maxScrollY

        val source = event.source
        val nodeDescription = source?.let { describeNode(it) } ?: "未知View"

        val log = """
        滑动事件:
        - 当前滚动: X=$scrollX, Y=$scrollY
        - 最大滚动: X=$maxScrollX, Y=$maxScrollY
        - 滑动的View: $nodeDescription
    """.trimIndent()
        writeLog(log)
    }

    private fun describeNode(node: AccessibilityNodeInfo): String {
        return "View描述: ${node.className}, 文本: ${node.text}, 内容描述: ${node.contentDescription}"
    }

    private fun handleNotification(event: AccessibilityEvent) {
        val notificationText = event.text?.joinToString("") ?: "未知通知"
        val log = "通知栏消息 - 内容: $notificationText\n"
        writeLog(log)
    }

    private val logFile by lazy { File(applicationContext.cacheDir, "user_actions.log") }
    private fun writeLog(log: String) {
        Log.i("AccessibilityLog", log)
        try {
//            FileOutputStream(logFile, true).bufferedWriter().use { writer ->
//                writer.append(log)
//            }
        } catch (e: Exception) {
            Log.e("AccessibilityLog", "日志写入失败: ${e.message}")
        }
    }

    private var wakeLock: WakeLock? = null

    override fun onServiceConnected() {
        super.onServiceConnected()
        val powerManager = getSystemService(POWER_SERVICE) as PowerManager

        // 创建 WakeLock，选择适合的唤醒锁类型
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AndroidAutoTask::WakeLock")

        // 获取唤醒锁
        wakeLock?.acquire()
    }

    override fun onStartCommand(intent: Intent, flah: Int, startID: Int): Int {
//        if (intent != null) {
//            if (intent.getIntExtra(SERVICE_FLAG, 0) == SERVER_OPEN_FOREGROUND) {
//                createNotification();
//            }
//        }
        return START_STICKY
    }

    override fun onDestroy() {
        super.onDestroy()
        releaseWakeLock()
    }


    //    private void createNotification() {
    //        NotificationManager notificationManager = (NotificationManager) getSystemService
    //                (Context.NOTIFICATION_SERVICE);
    //        String notificationId = "AutoTask";
    //        String notificationName = "自动化任务服务";
    //        int noticeId = 1;
    //        Notification.Builder builder = new Notification.Builder(this);
    //        //创建NotificationChannel
    //        if (SysUtil.OS_VERSION >= Build.VERSION_CODES.O) {
    //            NotificationChannel channel = new NotificationChannel(notificationId,
    //                    notificationName, NotificationManager.IMPORTANCE_HIGH);
    //            channel.enableLights(true);//设置高亮（选填）
    //            channel.setShowBadge(true);//设置角标（选填）
    //            //设置锁屏可见（选填）
    //            channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
    //            notificationManager.createNotificationChannel(channel);
    //            builder.setChannelId(notificationId);
    //        }
    //        Intent intent = new Intent(AutoTaskService.this, MainActivity.class);
    //        PendingIntent pendingIntent;
    //        //Android12
    //        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
    //            pendingIntent = PendingIntent.getActivity(this,
    //                    123, intent, PendingIntent.FLAG_IMMUTABLE);
    //        } else {
    //            pendingIntent = PendingIntent.getActivity(this,
    //                    123, intent, PendingIntent.FLAG_ONE_SHOT
    //                            | PendingIntent.FLAG_MUTABLE);
    //        }
    //        builder.setSmallIcon(R.drawable.ic_logo)
    //                .setContentTitle("运行中")//选填
    //                .setContentText("自动化任务服务")//选填
    //                .setWhen(System.currentTimeMillis())
    //                .setContentIntent(pendingIntent);
    //        Notification notification = builder.build();
    //        startForeground(noticeId, notification);
    //    }
    /**
     * 坐标模拟点击:最低api24，即要求Android7.0以上
     */
    private fun click(x: Float, y: Float) {
        if (x < 0f || y < 0f) {
            return
        }
        val builder = GestureDescription.Builder()
        val path = Path()
        path.moveTo(x, y)
        //path.lineTo(x, y)
        builder.addStroke(StrokeDescription(path, 0, 1))
        val gesture = builder.build()
        this.dispatchGesture(gesture, object : GestureResultCallback() {
        }, null)
    }


    //    /**
    //     * 寻找到可领取的红包节点，过滤掉过期的和已领取的红包
    //     *
    //     * @param node
    //     */
    //    private void findRedBagNodes(AccessibilityNodeInfo node) {
    //        if (node == null) {
    //            return;
    //        }
    //        //叶子节点
    //        if (node.getChildCount() == 0) {
    //            if (node.getText() != null) {
    //                if ("微信红包".equals(node.getText().toString())) {
    //                    AccessibilityNodeInfo parent = node.getParent();
    //                    //检查是否过期或者已经领取
    //                    for (int i = 0; i < parent.getChildCount(); i++) {
    //                        if (parent.getChild(i) != null && parent.getChild(i).getText() != null) {
    //                            if ("已领取".equals(parent.getChild(i).getText().toString())
    //                                    || "已过期".equals(parent.getChild(i).getText().toString())
    //                                    || "已被领完".equals(parent.getChild(i).getText().toString())) {
    //                                return;
    //                            }
    //                        }
    //                    }
    //                    result = node;
    //                }
    //            }
    //            //非叶子节点
    //        } else {
    //            for (int i = 0; i < node.getChildCount(); i++) {
    //                if (node.getChild(i) != null) {
    //                    findRedBagNodes(node.getChild(i));
    //                }
    //            }
    //        }
    //    }
    fun releaseWakeLock() {
        if (wakeLock != null && wakeLock!!.isHeld) {
            // 释放唤醒锁
            wakeLock!!.release()
        }
    }

    companion object {
        var TAG: String = "AutoTaskService"

        @JvmField
        var accessibilityService: AccessibilityService? = null

        var isLog: Boolean = true
    }
}
